package com.flycent.hqhs.ui;
import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.Brand;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.bean.ProductCategory.AppLayout;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.OverflowMenu;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 商品列表
 * @author fbl
 */
public class ProductListActivity extends BackableTitleBarActivity implements OnLoadDataActionListener, OnItemClickListener {
	@ViewInject(id = R.id.back_top_img ,click = "butClick") ImageView mBackTopImg;

	PullToRefreshGridView mRefreshGridView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private ProductListAdapter mAdapter;
	private int nowPage = 1;
	private String orderProperty = "id";
	private List<Product> mProducts;

	private long category_id	= 0;
	private AppLayout appLayout;
	// 查询条件
	private String query;
	private final String QUERY_ID = "goods.productCategory.id::eq::%1$d"; // category_id
	private final String QUERY_BRAND = "goods.productCategory.id::eq::%1$d,,brand.id::eq::%2$d"; // brand
	// 筛选
	private PageEntity<Brand> brands;
	private OverflowMenu menu;
	private Handler mHandler = new MyHandler(this);


	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_product_list);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.title_product_list);

		category_id = getIntent().getLongExtra("CATEGORY_ID", category_id);
		appLayout = AppLayout.GRID.name().equals(getIntent().getStringExtra("APP_LAYOUT")) ? AppLayout.GRID : AppLayout.LIST;

		mRefreshGridView = (PullToRefreshGridView) findViewById(R.id.product_list);
		mRefreshGridView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		if (appLayout == AppLayout.GRID) mRefreshGridView.getRefreshableView().setNumColumns(GridView.AUTO_FIT); // 2

		query = String.format(QUERY_ID, category_id);
		mAdapter = new ProductListAdapter(this, appLayout == AppLayout.LIST ? R.layout.list_item_products : R.layout.grid_item_products);
		mRefreshGridView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshGridView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();
		mRefreshGridView.setOnItemClickListener(this);

		menu = new OverflowMenu(this).setOnItemClickListener(this);

		mRefreshGridView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
			}

			@Override
			public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				if(arg1 != 0){  
					mBackTopImg.setVisibility(View.VISIBLE);
				}else {
					mBackTopImg.setVisibility(View.GONE);
				}
			}
		});

	}


	@Override
	public void onRefresh(int page) {
		nowPage = 1;
		updateProductList(true);
	}

	@Override
	public void onLoadMore(int page) {
		nowPage ++;
		updateProductList(false);
	}

	private void updateProductList(final boolean isRefresh){
		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				WebClient client = WebClient.getInstance(ProductListActivity.this);
				try {
					if (null == brands) {
						brands = client.productBrands(null, 1, 20, "id", "desc");
						// 加入【所有】
						Brand all = new Brand(); all.setName(getString(R.string.all_brand));
						brands.getContent().add(0, all);
						mHandler.sendEmptyMessage(2);
					}

					PageEntity<Product> entity = client.products(query, nowPage, 20, orderProperty, "desc");

					int totlePage = entity.getTotalPages();
					mProducts = entity.getContent();
					if(nowPage > totlePage){
						App.showShortToast(R.string.the_end_page);
						return;
					}
				} catch (WebException e) {
					if (!WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		mLoadMoreProxy.loadDataActionComplete(true);
	}

	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0: // refresh
					mAdapter.update(mProducts);

					break;
				case 1: // append
					mAdapter.append(mProducts);

					break;
				case 2: // menu
					if (null != brands) menu.setEntries(brands.getContent());

					break;
				default:
					break;
				}
			}
		}
	}


	public static class ProductListAdapter extends AbsViewHolderAdapter<Product>{

		public ProductListAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {

			ImageView mImageView = getViewFromHolder(R.id.item_time_limit_image);
			TextView mNameTextView = getViewFromHolder(R.id.item_time_limit_name_txt);
			TextView mPriceTextView = getViewFromHolder(R.id.item_time_limit_price_txt);
			TextView mMarketPriceTextView = getViewFromHolder(R.id.item_time_limit_market_price_txt);

			mMarketPriceTextView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

			ImageLoader.getInstance().displayImage(itemData.getImage(),mImageView);
			mNameTextView.setText(itemData.getName());
			mPriceTextView.setText("￥"+itemData.getPrice());
			mMarketPriceTextView.setText("￥"+itemData.getReferencePrice());
		}
	}



	@Override
	public void onBackPressed() {
		if (menu.isShown())
			menu.close();
		else
			super.onBackPressed();
	}

	public void butClick(View v){
		if( v == mBackTopImg ){
			mRefreshGridView.setSelection(0);
		}
	}

	public void onClick(View v) {
		if (menu.isShown())
			menu.close();
		else {
			switch (v.getId()) {
			case R.id.radio0: // 品牌
				menu.open();

				break;
			case R.id.radio1: // 最新
				orderProperty = "createDate";
				onRefresh(1);

				break;
			case R.id.radio2: // 销量
				orderProperty = "sales";
				onRefresh(1);

				break;
			case R.id.radio3: // 价格
				orderProperty = "price";
				onRefresh(1);

				break;

			default:
				break;
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		System.out.println(position);

		switch (parent.getId()) {
		case R.id.gridview: // 商品
			Intent intent = new Intent(ProductListActivity.this,ProductDetailActivity.class);
			intent.putExtra("productID", mAdapter.getData().get(position).getId()+"");
			startActivity(intent);

			break;
		case R.id.overflow_lv: 	// 筛选菜单
			orderProperty = "id";
			if (0 == position) {// 所有品牌
				((TextView) findViewById(R.id.radio0)).setText(getString(R.string.filter_brand));
				query = String.format(QUERY_ID, category_id);
			} else {
				((TextView) findViewById(R.id.radio0)).setText(brands.getContent().get(position).getName());
				query = String.format(QUERY_BRAND, category_id, brands.getContent().get(position).getId());
			}
			onRefresh(1);

			menu.close();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}
}
